<?php
/**
 * Created by PhpStorm.
 * User: 技术员专用
 * Date: 2019/2/15
 * Time: 14:15
 */

namespace app\admin\controller;

use Hanson\Vbot\Message\Text;
use Hanson\Vbot\Message\Emoticon;
use Illuminate\Support\Collection;
use Hanson\Vbot\Contact\Friends;
use Hanson\Vbot\Contact\Groups;
use Hanson\Vbot\Contact\Members;
use app\admin\controller\Tuling;
use app\admin\controller\Baidu;
class MessageHandler
{
    public static function messageHandler(Collection $message){
//        $friend=vbot('friend');
//
//        $members = vbot('members');
//
//        $groups = vbot('groups');
        $type=$message['type'];
        vbot('console')->log('Message Type：' . $type . ' From: ' . $message['from']['UserName']);
        $tuling=config('tuling');
        switch ($type) {
            case 'text':
                //@我或者好友发消息都自动回复
                if (true == $message['isAt'] || $message['fromType'] == 'Friend') {
                    if (strstr($message['pure'], '百度') !== false) {
                        $baidu   = new Baidu();
                        $return  = $baidu->search($message['pure']);
                        foreach ((array) $return as $key => $value) {
                            if (isset($value['title']) && isset($value['url'])) {
                                Text::send($message['from']['UserName'], $value['title'] . ' ' . $value['url']);
                            }
                        }
                    } else {
                        if ($message['from']['RemarkName']=='2'){
                            //指定人员发送命令
                            if (strstr($message['pure'],'wangyi')){
                                //发送单人信息
                                $str=str_replace('wangyi','',$message['pure']);
                                $info=explode('#',$str);
                                if (!empty($info[0])){
                                    $friends = vbot('friends');//好友实例
                                    $userInfo=$friends->getUsernameByRemarkName($info[0]);//根据备注获取信息
                                }
                                if (!empty($info[0])&&!empty($userInfo)){
                                    Text::send($userInfo,$info[1]);
                                }
                            }
                            if (strstr($message['pure'],'wangyis')){
                                //发送群信息
                                $str=str_replace('wangyis','',$message['pure']);
                                $info=explode('#',$str);
                                print_r($info);
                                if (!empty($info[0])){
                                    $group=vbot('groups');//群实例
                                    $groupInfo=$group->getGroupsByNickname($info[0]);//根据群名称获取群消息，返回数组，username：群信息，MemberList：群组所有成员消息
                                    print_r($groupInfo);
                                }
                                if (!empty($info[0])&&!empty($groupInfo)){
                                    Text::send($groupInfo['UserName'],$info[1]);
                                }
                            }
                        }else{
                            //图灵API回复
                            $tuling =new Tuling($tuling['params']);
                            $return =$tuling->search($message['pure']);
                            Text::send($message['from']['UserName'], $return);
                        }

                    }
                }

                break;
            case 'voice':
                // code...
                break;
            case 'image':
                // code...
                break;
            case 'emoticon':
                // code...
                break;
            case 'red_packet':
                // code...
                break;
            case 'share':
                // code...
                $myself=vbot('myself');
                $myself=$myself->nickname;
                print_r($myself);
                if ($message['title']=='邀请你加入群聊'){
                    $inviter=!empty($message['from']['RemarkName'])?$message['from']['RemarkName']:'无备注';
                    $user=db('users')->where(['remarkname'=>$inviter])->find();
                    if (!empty($user)){
                        $inviteMsg=$message['description'];
                        $inviteMsg=str_replace('，进入可查看详情。','',$inviteMsg);
                        $inviteGroup=str_replace('加入群聊','',substr($inviteMsg,strripos($inviteMsg,'加入群聊')));
                        $data=[
                            'users_id'=>$user['id'],
                            'myself'=>$myself,
                            'group'=>$inviteGroup,
                            'time'=>time(),
                            'day'=>date('Y-m-d'),
                        ];
                        db('groups')->insert($data);
//                        $user['money']=$user['money']+0.6;
//                        db('users')->update($user);
                    }


                }
                break;
            case 'new_friend':
                echo '新增好友' . 11 . '请求' . PHP_EOL;
                print_r($message['from']);
                Text::send($message['from']['UserName'], '客官，等你很久了！感谢跟 oop 交朋友，我是 kcloze 的贴身秘书，当你累了困惑了，可以随时呼叫我！' . PHP_EOL . '高山流水遇知音，知音不在谁堪听？焦尾声断斜阳里，寻遍人间已无');
                break;
            case 'request_friend':
                echo '新增好友' . $message['info']['NickName'] . '请求，自动通过' . PHP_EOL;
                $friends = vbot('friends');
                $friends->approve($message);
                $id=db('users')->insertGetId(['time'=>time()]);
                $friends->setRemarkName($message['info']['UserName'],$id);
                db('users')->update(['id'=>$id,'remarkname'=>$id]);
                break;
            case 'group_change':
                //action：ADD-增加成员 REMOVE-移除成员 RENAME-更改群名称 INVITE-被邀请进群 BE_REMOVE-被踢出群
                //inviter	邀请者昵称（仅 ADD 时存在）
                //invited	被邀请者昵称（仅 ADD 时存在）
                if ($message['action']=='INVITE'){
                    $inviters=explode('"',$message['content']);
                    print_r($inviters);
                    $inviter=$inviters[1];
                    $user=db('users')->where(['remarkname'=>$inviter])->find();
                    $user['money']=$user['money']+0.6;
                    db('users')->update($user);
                    $group=vbot('groups');//群实例
                    $asd=$group->get($message['from']['UserName']);
                    print_r($asd);
                }

                if ($message['action']=='ADD'){
//                    Text::send($message['from']['UserName'], '欢迎新人 ' . $message['invited'] . PHP_EOL . '邀请人：' . $message['inviter']);
                }
                break;
            default:
                // code...
                break;

        }

//        if ($message['fromType'] === 'Friend') {
//            vbot('console')->log('这是好友发送的消息');
//            Text::send($message['from']['UserName'], 'Vbot测试,我接收到你的消息了');
//        }
//        if ($message['fromType'] === 'Group') {
//            if($message['isAt']){
//                vbot('console')->log('这是好友发送的消息');
//                Text::send($message['from']['UserName'], 'Vbot测试,I was @');
//            }
//        }
    }

}